<template>
  <el-select
    :model-value="props.modelValue"
    filterable
    remote
    :reserve-keyword="false"
    :placeholder="props.placeholder"
    clearable
    :remote-method="remoteMethod"
    :loading="loading"
    style="width: 100%"
    @update:model-value="handleChange"
    @change="handleSelect"
  >
    <el-option v-for="item in selectData" :key="item.instructorId" :label="item.departmentLeader" :value="item.instructorId" />
  </el-select>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue'
  import { getInstructorListService } from '@/api/user'
  defineOptions({ name: 'RemoteSelect' })
  interface InstructorItem {
    instructorId: string
    departmentLeader: string
  }

  // Props
  interface Props {
    modelValue?: string
    placeholder?: string
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: null,
    placeholder: '请输入名字进行模糊搜索',
  })
  // Emits
  const emit = defineEmits<{
    'update:modelValue': [value: string]
    select: [nameLabel: string]
  }>()

  // Reactive data
  const loading = ref<boolean>(false)
  const selectData = ref<InstructorItem[]>([])

  // Methods
  /** 远程教师姓名搜索 */
  const remoteMethod = async (query: string) => {
    if (query) {
      loading.value = true
      try {
        // 调用远程接口获取数据
        selectData.value = await getInstructorListService(query)
      } catch (error) {
        selectData.value = []
      } finally {
        loading.value = false
      }
    } else {
      selectData.value = []
    }
  }

  /** 远程搜索框选择了值，然后通知父组件去修改*/
  const handleChange = (value: string) => {
    const selectedInstructor = selectData.value.find((item) => item.instructorId === value)
    emit('update:modelValue', selectedInstructor?.departmentLeader || '')
  }

  /** 处理选择事件 - 传递真实id */
  const handleSelect = (value: number | string | null) => {
    const selectedInstructor = selectData.value.find((item) => item.instructorId === value) || null
    emit('select', selectedInstructor?.instructorId || '')
  }
</script>
